package cn.apestar.common.image;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageTools {

	/**
	 * 生成图片所略图 oldpath原图地址 savepath缩略图地址 pic_w缩略图宽度
	 * 
	 * @param oldpath
	 * @param savepath
	 * @float pic_w
	 * @return
	 */

	public static void toZipJpg(String oldpath, String savepath, float pic_w)
			throws Exception {

		File objPic = new File(savepath); // 判断有无图片,也是缩略图保存路径
		String picname = "";
		String cName = savepath;	
		try {
			
			if (oldpath.indexOf("/") > -1) {
				picname = savepath.substring(savepath.lastIndexOf("/") + 1,
						savepath.length()); // linux路径判断
				savepath = savepath.substring(0, savepath.lastIndexOf("/"));
			} else {
				picname = savepath.substring(savepath.lastIndexOf("\\") + 1,
						savepath.length()); // win路径判断
				savepath = savepath.substring(0, savepath.lastIndexOf("\\"));
			}
			//System.out.println("oldpath="+oldpath);
			//System.out.println("savepath="+savepath);

			if (!objPic.exists()) { // 如果缩略图找不到

				File file = new File(oldpath); // 读入原图文件

				File saveFile = new File(savepath); // 保存地址判断
				if (!saveFile.exists()) {
					// System.out.println("没有文件夹");
					saveFile.mkdirs();
				}
				Image src = null;
				src = ImageIO.read(file); // 构造Image对象

				float tagsize = pic_w;
				int old_w = src.getWidth(null); // 得到源图宽
				int old_h = src.getHeight(null);
				int new_w = 0;
				int new_h = 0; // 得到源图长
				int tempsize;
				if(old_w<tagsize){
					
					tagsize=old_w;
					//如果是小图，按原比例压缩,原图copy一份
					Tools.copyFile(oldpath, cName);
				}else
				{
					//如果大图,按比例缩略,并压缩容量质量
					float tempdouble;
					if (old_w > old_h) {
						tempdouble = old_w / tagsize;
					} else {
						tempdouble = old_h / tagsize;
					}
					new_w = Math.round(old_w / tempdouble);
					new_h = Math.round(old_h / tempdouble); // 计算新图长宽
					BufferedImage tag = new BufferedImage(new_w, new_h,
							BufferedImage.TYPE_INT_RGB);
					tag.getGraphics().drawImage(src, 0, 0, new_w, new_h, null); // 绘制缩小后的图
	
					ImageIO.write(tag, "jpg", new File(saveFile,
							picname));
					tag = null;
				}
			}
		} catch (IOException ex) {
			System.out.println("toZipJpg is error");
		}

	}

	/*
	 * 
	 * 
	 * 2008-7-2 ws 此程序为了判断图片是否4:3 url原图地址
	 */

	public boolean isPic(String url) {

		int old_w = 0;
		int old_h = 0;
		try {
			File file = new File(url); // 读入原图文件
			Image src = ImageIO.read(file);

			old_w = src.getWidth(null); // 得到源图宽
			old_h = src.getHeight(null);
			src = null;

		} catch (Exception e) {
			System.out.println("判断图出现异常 isPic error :" + e);
		}
		if ((old_w - old_h) >= 20)
			return true;
		else
			return false;

	}
	
	/*
	 * 
	 * 
	 * 2010-8-27 ws 根据原图原比例缩小后得出高宽  url原图地址
	 */

	public static String ToZoom(String url,int width,int height) {

		float old_w = 0;
		float old_h = 0;
		float new_w = 0;
		float new_h = 0;
		float x = 0;
		String str = "0,0";
		try {
			File file = new File(url); // 读入原图文件
			Image src = ImageIO.read(file);

			old_w = src.getWidth(null); // 得到源图宽
			old_h = src.getHeight(null);
			src = null;
			if(width==0)
			{
				//按高度缩
				if(old_w>old_h){
					x = old_w/old_h;
					new_w = height * x;
					new_h = height;
				}
				else {
					x = old_w/old_h;
					new_w = height * x;
					new_h = height;
				}
			}else if(height==0)
			{
				//按宽度缩
				if(old_w>old_h){
					x = old_h/old_w;
					new_h = width * x;
					new_w = width;
				}
				else {
					x = old_h/old_w;
					new_h = width* x;
					new_w = width;
				}
			}
			new_w = (float)(Math.round(new_w*1))/1;
			new_h = (float)(Math.round(new_h*1))/1;
			//System.out.println(new_w+"_"+new_h);
			str = (int)new_w+","+(int)new_h;

		} catch (Exception e) {
			str = "480,270";
			//System.out.println("比例缩小图出现异常 ToZoom error :" + e);
		}

		return str;

	}
	
	
	/**
	 * 图片水印
	 * @param pressImg 水印图片
	 * @param targetImg 目标图片
	 * @param saveImg 另存图片
	 * @param x 修正值 默认在中间
	 * @param y 修正值 默认在中间
	 * @param alpha 透明度
	 */
	public final static void pressImage(String pressImg, String targetImg,String saveImg, int x, int y, float alpha) {
		try {
			File img = new File(targetImg);
			Image src = ImageIO.read(img);
			int wideth = src.getWidth(null);
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			g.drawImage(src, 0, 0, wideth, height, null);
			//水印文件
			Image src_biao = ImageIO.read(new File(pressImg));
			int wideth_biao = src_biao.getWidth(null);
			int height_biao = src_biao.getHeight(null);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
			g.drawImage(src_biao, (wideth - wideth_biao) / 2, (height - height_biao) / 2, wideth_biao, height_biao, null);
			//水印文件结束
			g.dispose();
			//ImageIO.write((BufferedImage) image, "jpg", img);
			ImageIO.write((BufferedImage) image,"jpg",new File(saveImg));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 文字水印
	 * @param pressText 水印文字
	 * @param targetImg 目标图片
	 * @param saveImg 另存图片
	 * @param fontName 字体名称
	 * @param fontStyle 字体样式
	 * @param color 字体颜色
	 * @param fontSize 字体大小
	 * @param x 修正值
	 * @param y 修正值
	 * @param alpha 透明度
	 */
	public static void pressText(String pressText, String targetImg,String saveImg, String fontName, int fontStyle, Color color, int fontSize, int x, int y, float alpha) {
		try {
			File img = new File(targetImg);
			Image src = ImageIO.read(img);
			int width = src.getWidth(null);
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			g.drawImage(src, 0, 0, width, height, null);
			g.setColor(color);
			g.setFont(new Font(fontName, fontStyle, fontSize));
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
			//System.out.println(height+"_"+fontSize);
			g.drawString(pressText, (width - (getLength(pressText) * fontSize)) / 2 + x, (height/2)  + y);
			g.dispose();
			//ImageIO.write((BufferedImage) image, "jpg", img);
			ImageIO.write((BufferedImage) image,"jpg",new File(saveImg));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 缩放
	 * @param filePath 图片路径
	 * @param height 高度
	 * @param width 宽度
	 * @param bb 比例不对时是否需要补白
	 */
	public static void resize(String filePath, int height, int width, boolean bb) {
		try {
			double ratio = 0.0; //缩放比例 
			File f = new File(filePath);
			BufferedImage bi = ImageIO.read(f);
			Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
			//计算比例
			if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
				if (bi.getHeight() > bi.getWidth()) {
					ratio = (new Integer(height)).doubleValue() / bi.getHeight();
				} else {
					ratio = (new Integer(width)).doubleValue() / bi.getWidth();
				}
				AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
				itemp = op.filter(bi, null);
			}
			if (bb) {
				BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				Graphics2D g = image.createGraphics();
				g.setColor(Color.white);
				g.fillRect(0, 0, width, height);
				if (width == itemp.getWidth(null))
					g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
				else
					g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
				g.dispose();
				itemp = image;
			}
			ImageIO.write((BufferedImage) itemp, "jpg", f);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static int getLength(String text) {
		int length = 0;
		for (int i = 0; i < text.length(); i++) {
			if (new String(text.charAt(i) + "").getBytes().length > 1) {
				length += 2;
			} else {
				length += 1;
			}
		}
		return length / 2;
	}
	
	public static void pressImgText(String pressText, String targetImg,String saveImg) {
		pressText(pressText, targetImg, saveImg,"黑体", 36, Color.white, 33, 0, 0, 0.5f);
	}
	
	public static void main(String[] args) {

		try {
			// String str = Tools.readFile("d:/pie.xml", "utf-8").toString();
			//System.out.println("111");
			// Tools.writeFile("d:/tt.xml", str, "utf-8");
			int w = 0;
			int h = 300;
			//System.out.println(ImageTools.ToZoom("e:\\temp\\2.jpg",0, 300));
			
			String path = System.getProperty("user.dir")+"\\1.jpg";
			
			String spath = System.getProperty("user.dir")+"\\2.jpg";
			
			String sypath = System.getProperty("user.dir")+"\\s.jpg";
			System.out.println(path+"_"+spath);
			
			//pressImage(sypath, path,spath, 0, 0, 0.5f);
			pressText("惠多网 138do.com", path, spath,"宋体", 36, Color.white, 16, 0, 0, 0.6f);
			//resize("G:\\imgtest\\test1.jpg", 500, 500, true);
			
		} catch (Exception ex) {
		}
	}
}
